package com.fengwk.support.spring.boot.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.ResultUtils;
import com.fengwk.support.util.TypeUtils;
import com.fengwk.support.util.LoggerUtils.Logger;

public abstract class AbstractControllerExceptionHandlerConfig {

	protected static final Logger LOG = LoggerUtils.getLogger(AbstractControllerExceptionHandlerConfig.class);
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	
	@ExceptionHandler
	public void resolveException(Throwable e) {
	    LOG.error(e);
		if(TypeUtils.isType(e.getClass(), BaseException.class)) {
			BaseException baseException = (BaseException) e;
			// BaseException
			ResultUtils.setCode(baseException.getCode());
			ResultUtils.setAttributes(baseException.getErrorMap());
		}else {
			// 系统错误
			ResultUtils.setCode(ResultUtils.SYSTEM_ERROE_CODE);
		}
		ResultUtils.setMessage(e.getMessage());
		ResultUtils.returnJsonResult(request, response);
	}
	
}
